package com.qianheng.kit.web.support;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * http请求中的参数是流的形式，消费一次就无法再次获取。 想要在业务中获取http参数，就需要先将其包装缓存起来。
 */
@Slf4j
@Order(1)
@Component
public class CachingWrapperOncePerRequestFilter extends OncePerRequestFilter {

    @Value("${qh.OncePerRequestFilter1.demo:}")
    private String demo;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
        if (request.getRequestURI().equals(demo)) {
            chain.doFilter(request, response);
            return;
        }

        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
        try {
            chain.doFilter(requestWrapper, responseWrapper);
        } finally {
            try {
                //
            } catch (Exception e) {
                log.error("append", e);
            } finally {
                responseWrapper.copyBodyToResponse();
            }

        }

    }
}
